package com.niuwa.p2p.action.role;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.niuwa.p2p.action.JsonAction;
import com.niuwa.p2p.action.user.UserAction;
import com.niuwa.p2p.core.mvc.entity.JsonResult;
import com.niuwa.p2p.core.mvc.entity.PageBean;
import com.niuwa.p2p.entity.role.Role;
import com.niuwa.p2p.entity.role.RoleResource;
import com.niuwa.p2p.service.resource.ResourcesService;
import com.niuwa.p2p.service.role.RoleResourceService;
import com.niuwa.p2p.service.role.RoleService;
import com.opensymphony.xwork2.ModelDriven;

@Controller
public class RoleAction extends JsonAction implements ModelDriven<Object> {
	private static final long serialVersionUID = 8519914189629693954L;

	private static Logger logger = Logger.getLogger(RoleAction.class);
	
	//返回页面信息
	String message;
	
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	@Autowired
	private RoleService roleService;

	@Autowired
	private ResourcesService resourceService;
	
	@Autowired
	private RoleResourceService roleResourceService;
    //角色
	private Role role;
	//角色资源
	private RoleResource roleResource;
	//角色ID
	private Integer roleId;
	//用户ID
	private Integer userId;
	// 角色Id数组
	private String[]  rowIdArr;
	
	//登入名
	private String loginName;
 
	

	/**
	 * 跳转至角色列表页面
	 * 
	 * @return
	 */
	@Action("gotoRoleList")
	public String gotoRoleList() {
		
		logger.info("goto role list!");
		return "roleList";
	}

	
	
	
	/**
	 * 
	 *根据用户名查询对应角色
	 *@param loginName
	 *@return List<Role>
	 *
	 */
	@Action("searchRolesByloginName")
	public String searchRolesByloginName(){
		 JsonResult results=new JsonResult();
		 results.setData(roleService.searchRolesByloginName(loginName));
		 setResult(results);
		return NONE;
	}
	
	/**
	 * 跳转至授予角色列表页面
	 * 
	 * @return
	 */
	@Action("gotoAuthorizeRolePage")
	public String gotoAuthorizeRolePage() {
		
		logger.info("goto role list!");
		return "authorizeRole";
	}
	/**
	 * 角色列表
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "roleList")
	public String roleList() throws Exception {
		setObjectReSult(queryPagination());
		logger.info("roleList action execute success");
		return NONE;
	}

	/**
	 * 资源列表
	 * @return
	 * @throws Exception
	
	@Action(value = "resouList")
	public String resouList() throws Exception {
		setObjectReSult(resourceService.getResource());
		logger.info("resouList execute success");
		return NONE;
	}
 */
	/**
	 * 资源列表
	 * @return
	 * @throws Exception
	 */
	@Action(value = "getResourceByRoleId")
	public String getResourceByRoleId() throws Exception {
		setResult(new JsonResult(resourceService.getResourceByRoleId(Integer.parseInt(role.getId()))));
		logger.info("resouList execute success");
		return NONE;
	}

	/**
	 * 角色新增
	 * @return
	 * @throws Exception
	 */
	@Action(value = "addRole")
	public String addRole() throws Exception {
	              Long userId=   UserAction.getSessionUser().getId();  
	              JsonResult results=new JsonResult();
		try {
			List<Role> roleList=roleService.searchRoleByName(role);
			 if(roleList.size()!=0){
				 message="角色名重复,新增失败";
				 throw new RuntimeException();
			 }else{
				 roleService.addRole(role,userId); 
				 message="新增成功";
				 results.setMsg(message);
				 setResult(results);
			 }
		} catch (Exception e) {
			if(!("角色名重复,新增失败".equalsIgnoreCase(message))){
			   message="新增失败";
			}
			 results.setMsg(message);
			  setResult(results);
			  e.printStackTrace();	
		}
		return NONE;            
		
	}
	
	
	
	/**
	 * 角色修改
	 * @return
	 * @throws Exception
	 */
	@Action(value = "updateRole")
	public String updateRole() throws Exception {
	             
	              JsonResult results=new JsonResult();
		try {
			   Role role2=roleService.getRoleById(roleId);
			 if(role2==null){
				 message="角色不存在,修改失败";
				 throw new RuntimeException();
			 }else{
				 roleService.updateRole(role,roleId); 
				 message="修改成功";
				 results.setMsg(message);
				 setResult(results);
			 }
		} catch (Exception e) {
			if(!(message.equalsIgnoreCase("角色不存在,修改失败"))){
			   message="修改失败";
			}
			 results.setMsg(message);
			  setResult(results);
			  e.printStackTrace();	
		}
		return NONE;            
		
	}
	
	
	
	/**
	 * 跳转角色修改页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "gotoUpdateRolePage")
	public String gotoUpdateRolePage() throws Exception {
		role=roleService.getRoleById(roleId);
		return "updateRolePage";
	}
	
	/**
	 * 角色删除
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "roleDelete")
	public String changeRoleStatus() throws Exception {
		
		try {
			setResult(roleService.changeRoleStatus(roleId));
		} catch (Exception e) {
			logger.info("角色删除失败");
			e.printStackTrace();
		} 
		
		return NONE;
	}
	
	
	/**
	 * 
	 * 跳转到角色增加页面
	 * @return
	 * @throws Exception
	 */
	@Action(value = "gotoAddRolePage")
	public String gotoAddRolePage() throws Exception {
	
		return "addRolePage";
	}
	
	
	/**
	 * 
	 *用户授予角色
	 *@param
	 *
	 */
	@Action(value = "authorizeRole")
	public void authorizeRole(){
		JsonResult results=new JsonResult();
		try {
			HttpServletRequest request=ServletActionContext.getRequest();
			String[]  rowIdArr=request.getParameterValues("rowIdArr[]");
			roleService.updateUserRole(userId,rowIdArr);
			message="授于角色成功";
			results.setMsg(message);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			message="授于角色失败";
			results.setMsg(message);
		}
		setResult(results);
	}
	/**
	 * 绑定角色、资源关系
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "bindRoleResource")
	public String bindRoleResource() throws Exception {
		setResult(roleResourceService.saveRoleResource(roleResource));
		return NONE;
	}
  
	/**
	 * 
	 *查询所有角色
	 *@rerurn  
	 *
	 */
	@Action(value = "searchAllRoles")
	public String searchAllRoles(){
		setObjectReSult(roleService.searchAllRoles());
		return NONE;
	}
	/**
	 * 解绑角色、资源关系
	 * 
	 * @return
	 * @throws Exception
	 
	@Action(value = "unbindRoleResource")
	public String unbindRoleResource() throws Exception {
		setResult(roleResourceService.deleteRoleResource(roleResource));
		return NONE;
	}*/

	/**
	 * 分页查询
	 * 
	 * @return Pagination<Role>
	 */
	private PageBean<Role> queryPagination() {
		// 获取查询参数
		Map<String, Object> paramMap = getParamMap();
		// 执行查询操作
		PageBean<Role> pagination = roleService.search(paramMap);
		return pagination;
	}

	@Override
	public Object getModel() {
		if (role == null) {
			role = new Role();
		}
		return role;
	}

	public Role getRole() {
		return role;
	}

	public void setRole(Role role) {
		this.role = role;
	}

	public RoleResource getRoleResource() {
		return roleResource;
	}

	public void setRoleResource(RoleResource roleResource) {
		this.roleResource = roleResource;
	}
	

	
	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public ResourcesService getResourceService() {
		return resourceService;
	}

	public void setResourceService(ResourcesService resourceService) {
		this.resourceService = resourceService;
	}

	public RoleResourceService getRoleResourceService() {
		return roleResourceService;
	}

	public void setRoleResourceService(RoleResourceService roleResourceService) {
		this.roleResourceService = roleResourceService;
	}

	public Integer getRoleId() {
		return roleId;
	}

	public void setRoleId(Integer roleId) {
		this.roleId = roleId;
	}

	

	public String[] getRowIdArr() {
		return rowIdArr;
	}

	public void setRowIdArr(String[] rowIdArr) {
		this.rowIdArr = rowIdArr;
	}

	public Integer getUserId() {
		return userId;
	}

	public void setUserId(Integer userId) {
		this.userId = userId;
	}

	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}
}
